const helper = require("../helper/helper");
const { parse, join } = require("path");
// const sharp = require("sharp");
const OSS = require("ali-oss");
const { v4 } = require("uuid");
const path = require("path");
const { uploadPath } = require("../config");
const { accessKeyId, accessKeySecret } = require("../config");
const { renderPageService } = require("../service/utileService");
const client = new OSS({
  accessKeyId,
  accessKeySecret,
  bucket: "lego-express",
  endpoint: "oss-cn-shanghai.aliyuncs.com",
});
async function uploadFileToOSS(file, client) {
  const fileBuffer = file.buffer;
  const fileName = path.basename(file.originalname); // 防止路径注入
  const saveOSS = `express-test/${v4()}/${fileName}`;
  try {
    const result = await client.put(saveOSS, fileBuffer);
    return result.url;
  } catch (error) {
    // 可以选择记录错误或返回一个表示失败的对象
    console.error(`Failed to upload file: ${fileName}`, error);
    throw new Error(`Failed to upload ${fileName}: ${error.message}`);
  }
}
function splitIdAndUuid(str) {
  const result = { id: "", uuid: "" };
  const splitIndex = str.indexOf("-");
  if (splitIndex < 0) {
    return result;
  }
  result.id = str.slice(0, splitIndex);
  result.uuid = str.slice(splitIndex + 1);
  return result;
}
const fileType = ["image/jpeg", "image/png", "image/webp"];
module.exports = {
  async uploadContorller(req, res) {
    // console.log(req.file);
    // const filtPath = req.file.path;
    // const url = join(uploadPath, "/", filtPath)
    //   .replace("\\public\\", "/")
    //   .replace("uploads\\", "uploads/");
    // let thoumbnailUrl = "";
    // const imageSouce = sharp(filtPath);
    // const meatData = await imageSouce.metadata();
    // console.log(meatData);

    // if (meatData.width > 300) {
    //   const { name, ext, dir } = parse(filtPath);
    //   const thoumbnailPath = join(dir, name + "-thoumbnail" + ext);
    //   console.log(thoumbnailPath);

    //   await imageSouce.resize({ width: 300 }).toFile(thoumbnailPath);
    //   thoumbnailUrl = join(
    //     uploadPath,
    //     "/uploads/",
    //     name + "-thoumbnail" + ext
    //   ).replace("\\uploads\\", "/uploads/");
    // }
    // return helper.successMessage({ res, data: { url, thoumbnailUrl } });
    return helper.successMessage({ res })
  },

  async uploadOSSContorller(req, res) {
    const files = req.files || []; // 确保 files 存在，即使为空数组
    console.log(files);

    let fileError = false;
    files.forEach((file) => {
      if (!fileType.includes(file.mimetype)) {
        fileError = true;
      } else if (file.size > 1024 * 1024 * 15) {
        fileError = true;
      }
    });
    if (fileError) {
      return helper.errorMessage({ res, errCode: "uploadFileTypeError" });
    }
    const urls = [];
    const uploadPromises = files.map((file) => uploadFileToOSS(file, client));

    try {
      urls.push(...(await Promise.all(uploadPromises))); // 使用 Promise.all 等待所有上传完成
      helper.successMessage({ res, data: urls }); // 所有文件上传成功
    } catch (error) {
      // 捕获任何上传过程中的错误，并返回错误信息
      // 注意：这里捕获的是由 uploadFileToOSS 函数抛出的错误
      helper.errorMessage({ res, error, errCode: "uploadFileError" });
    }
  },
  //ssr渲染页面
  async ssrRenderPage(req, res) {
    const { idAndUuid } = req.params;
    const result = splitIdAndUuid(idAndUuid);
    try {
      const { desc, title, html, bodyStyle } = await renderPageService(result);

      return res.render("ssr-template.nj", { desc, title, html, bodyStyle });
    } catch (error) {
      return helper.errorMessage({ res, error, errCode: "pageRenderError" });
    }
  },
};
